//
//  RollCollectionViewCell.swift
//  CompareBuying
//
//  Created by 唐先才 on 16/2/3.
//  Copyright © 2016年 唐先才. All rights reserved.
//

import UIKit

class RollCollectionViewCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    var model: TxcModel?
    var collectionView: UICollectionView?
    var dataArray: NSMutableArray = []
    var time: NSTimer?
    var pc: UIPageControl?
    var viewController: UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.createTimer()
        self.createUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func createTimer() {
        time = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "runLoop", userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(time!, forMode: NSRunLoopCommonModes)
    }
    /*
       此处应将整个collectionView封装到一个UIView当中，直接调用
    */
    func createUI() {
        if collectionView == nil && pc == nil {
            let layout = UICollectionViewFlowLayout()
            layout.scrollDirection = .Horizontal
            layout.minimumLineSpacing = 0
            collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: 200), collectionViewLayout: layout)
            guard let collectionView = collectionView else {
                return
            }
            collectionView.backgroundColor = UIColor.whiteColor()
            self.contentView.addSubview(collectionView)
            collectionView.dataSource = self
            collectionView.delegate = self
            collectionView.pagingEnabled = true
            collectionView.contentOffset = CGPointZero
            let nib1 = UINib(nibName: "RollingCell", bundle: NSBundle.mainBundle())
            collectionView.registerNib(nib1, forCellWithReuseIdentifier: "rollingCell")
//            //创建pc
//            pc = UIPageControl(frame: CGRect(x: WIDTH / 4, y: 200 - 20, width: WIDTH / 2, height: 20))
//            guard let pc = pc else {
//                return
//            }
//            pc.currentPage = 1
//            pc.numberOfPages = self.dataArray.count
//            pc.pageIndicatorTintColor = UIColor.redColor()
//            self.contentView.addSubview(pc)
        }
    }
    
//    func scrollViewDidScroll(scrollView: UIScrollView) {
//        guard let collectionView = collectionView, pc = pc else {
//            print("滑动方法失败")
//            return
//        }
//        let page = collectionView.contentOffset.x / self.frame.size.width
//        pc.currentPage = Int(page)
//    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.removeTimer()
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.createTimer()
    }
    
    func removeTimer() {
        guard let time = self.time else {
            print("移除定时器失败")
            return
        }
        time.invalidate()
    }
    
    func runLoop() {
        guard let collectionView = collectionView else {
            print("循环失败")
            return
        }
        
        let currentIndexPath = collectionView.indexPathsForVisibleItems().last
        guard let newCurrentIndexPath = currentIndexPath else {
            return
        }
        let nextItem = newCurrentIndexPath.item + 1
        let nextSection = newCurrentIndexPath.section
        let nextIndexPath = NSIndexPath.init(forItem: nextItem, inSection: nextSection)
        collectionView.scrollToItemAtIndexPath(nextIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        
//        collectionView.setContentOffset(<#T##contentOffset: CGPoint##CGPoint#>, animated: <#T##Bool#>)
//        let w = self.frame.size.width
//        pc.currentPage = Int(collectionView.contentOffset.x / w)
//        if collectionView.contentOffset.x == CGFloat(self.dataArray.count) * w {
//            pc.currentPage = 0
//        }
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count * 1000
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        if let rollingCell = collectionView.dequeueReusableCellWithReuseIdentifier("rollingCell", forIndexPath: indexPath) as? RollingCell {
            if self.dataArray.count > 0 {
                if let model = self.dataArray[indexPath.item % self.dataArray.count] as? TxcModel {
                    rollingCell.configCellWithModel(model)
                }
            }
            return rollingCell
        }
        return UICollectionViewCell()
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(WIDTH, 200)
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0, 0, 0, 0)
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("我被点击了")
        let dvc = DetailViewController()
        let home = HomePageViewController()
        home.initWithClosure { (goViewController) -> Void in
            let h = goViewController
            print("***\(h.navigationController)**")
        }

        
//        h.navigationController.pushViewController(dvc, animated: true)
        
    }
}
